from django.contrib.auth.models import AnonymousUser
from rest_framework.pagination import PageNumberPagination
from rest_framework.throttling import AnonRateThrottle


class CustomPagination(PageNumberPagination):
    """自定义分页器"""
    page_size_query_param = 'size'
    max_page_size = 50


class CustomThrottle(AnonRateThrottle):
    """自定义限流类"""
    scope = 'custom'
    THROTTLE_RATES = {'custom': '5/min'}

    def get_cache_key(self, request, view):
        if request.user and not isinstance(request.user, AnonymousUser):
            ident = request.user.userid
        else:
            ident = self.get_ident(request)

        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }
